package com.software.myopiachildren.ui;


import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.software.myopiachildren.R;
import com.software.myopiachildren.base.BaseActivity;
import com.software.myopiachildren.content.Constant;
import com.software.myopiachildren.utils.ToastUtil;
import com.software.myopiachildren.utils.eb.EB;
import com.software.myopiachildren.utils.eb.EbData;
import com.software.myopiachildren.utils.recoder.AudioRecoderUtils;
import com.software.myopiachildren.utils.recoder.TimeUtils;
import com.software.myopiachildren.utils.sp.SP;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 预警提示音
 *
 * @author penglei
 * @date 2020/05/13
 */
public class WarningActivity extends BaseActivity {
    private static final String TAG = "WarningActivity";

    @BindView(R.id.iv_title_left)
    ImageView mIvTitleLeft;
    @BindView(R.id.tv_title_text)
    TextView mTvTitleText;
    @BindView(R.id.tv_title_right)
    TextView mTvTitleRight;
    @BindView(R.id.lay_title_home)
    LinearLayout mLayTitleHome;

    @BindView(R.id.rb_worning_system)
    RadioButton mRbWorningSystem;
    @BindView(R.id.iv_worning_system_img)
    ImageView mIvWorningSystemImg;
    @BindView(R.id.tv_worning_system_name)
    TextView mTvWorningSystemName;
    @BindView(R.id.iv_worning_system_player_img)
    ImageView mIvWorningSystemPlayerImg;
    @BindView(R.id.ll_worning_system)
    LinearLayout mLlWorningSystem;
    @BindView(R.id.rb_worning_mine)
    RadioButton mRbWorningMine;
    @BindView(R.id.iv_worning_mine_img)
    ImageView mIvWorningMineImg;
    @BindView(R.id.tv_worning_mine_name)
    TextView mTvWorningMineName;
    @BindView(R.id.iv_worning_mine_player_img)
    ImageView mIvWorningMinePlayerImg;
    @BindView(R.id.ll_worning_mine)
    LinearLayout mLlWorningMine;

    @BindView(R.id.tv_worning_recording_time)
    TextView mTvWorningRecordingTime;
    @BindView(R.id.ll_worning_recording_time)
    LinearLayout mLlWorningRecordingTime;
    @BindView(R.id.tv_worning_recording)
    TextView mTvWorningRecording;

    private AudioRecoderUtils mAudioRecoderUtils;
    private MediaPlayer player; // 音频播放
    private long ltime;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_warning;
    }

    @Override
    public void initView() {
        mTvTitleText.setText(getResources().getString(R.string.s_warning));

        // 设置RadioButton监听点击事件为false
        mRbWorningSystem.setClickable(false);
        mRbWorningSystem.setEnabled(false);
        mRbWorningSystem.setFocusable(false);
        mRbWorningMine.setClickable(false);
        mRbWorningMine.setEnabled(false);
        mRbWorningMine.setFocusable(false);

        initVedio();
        getWarningType();
        getPermissions(); // 判断权限
        initOnTouch(); // OnTouch事件
    }

    @Override
    public void initData() {

    }

    @Override
    protected void onDestroy() {
        if (player != null) {
            player.stop();
            player.release();
        }
        super.onDestroy();

    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @OnClick({R.id.iv_title_left, R.id.ll_worning_system, R.id.ll_worning_mine, R.id.iv_worning_system_player_img, R.id.iv_worning_mine_player_img, R.id.tv_worning_recording})
    public void onClick(final View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;

            case R.id.ll_worning_system:
                mRbWorningSystem.setChecked(true);
                mRbWorningMine.setChecked(false);
                new SP().save(Constant.WARNING_TYPE, 1);
                EB.post(new EbData(14));
                break;

            case R.id.ll_worning_mine:
                mRbWorningSystem.setChecked(false);
                mRbWorningMine.setChecked(true);
                new SP().save(Constant.WARNING_TYPE, 2);
                EB.post(new EbData(14));
                break;

            case R.id.iv_worning_system_player_img:
                onPlaySystemVedio();
                break;

            case R.id.iv_worning_mine_player_img:
                onPlayVedio();
                break;

            case R.id.tv_worning_recording:
                getPermissions();
                break;
        }
    }


    /**
     * 预警提示音类型
     */
    private void getWarningType() {
        // 预警提示音
        int warning_type = new SP().load(Constant.WARNING_TYPE, 0);
        if (warning_type == 1) {
            mRbWorningSystem.setChecked(true);
            mRbWorningMine.setChecked(false);
        } else if (warning_type == 2) {
            mRbWorningSystem.setChecked(false);
            mRbWorningMine.setChecked(true);
        }
    }


    /**
     * 检测权限
     */
    private void getPermissions() {
        AndPermission.with(this)
                .permission(Permission.RECORD_AUDIO, Permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Log.e(TAG, "===权限通过");
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Uri packageURI = Uri.parse("package:" + getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        ToastUtil.showShort("没有权限无法录音呦");
                    }
                }).start();
    }


    //录音功能 初始化
    private void initVedio() {
        // 判断录音文件是否为空
        if (!TextUtils.isEmpty(new SP().load(Constant.RECORD_PATH_ABSOULT, ""))) {
            mTvWorningRecording.setText(getResources().getString(R.string.s_warning_restart_recording));
        } else {
            mTvWorningRecording.setText(getResources().getString(R.string.s_warning_start_recording));
        }

        mAudioRecoderUtils = new AudioRecoderUtils();
        //录音回调
        mAudioRecoderUtils.setOnAudioStatusUpdateListener(new AudioRecoderUtils.OnAudioStatusUpdateListener() {
            @Override
            public void onUpdate(double db, long time) {
                ltime = time;
                Log.e(TAG, "===time:" + time);
                mTvWorningRecordingTime.setText(TimeUtils.getDateCoverString(time));
            }

            @Override
            public void onStop(String filePath) {
                Log.e(TAG, "===filePath:" + filePath);
                if (ltime < 1500) {//判断，如果录音时间小于1.5秒，则删除文件提示，过短
                    File file = new File(filePath);
                    if (file.exists()) {//判断文件是否存在，如果存在删除文件
                        file.delete();//删除文件
                        ToastUtil.showShort("录音时间过短");
                    }
                } else {
                    try {
                        //保存录音路径前先删除旧的文件
                        if (!TextUtils.isEmpty(new SP().load(Constant.RECORD_PATH_ABSOULT, ""))) {
                            File file = new File(new SP().load(Constant.RECORD_PATH_ABSOULT, ""));
                            if (file.exists()) {//判断文件是否存在，如果存在删除文件
                                file.delete();//删除文件
                            }
                        }

                        new SP().save(Constant.RECORD_PATH_ABSOULT, filePath);  // 录音文件
                        ToastUtil.showShort("录音保存在：" + filePath);
                        ltime = 0;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }

    private void initOnTouch() {
        mTvWorningRecording.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        //开始录音
                        mAudioRecoderUtils.startRecord();
                        mTvWorningRecording.setText(getResources().getString(R.string.s_warning_stop_recording));
                        mTvWorningRecording.setBackgroundColor(getResources().getColor(R.color.color_B6601E));
                        mLlWorningRecordingTime.setVisibility(View.VISIBLE);
                        break;

                    case MotionEvent.ACTION_UP:
                        //结束录音（保存录音文件）
                        mAudioRecoderUtils.stopRecord();
                        mTvWorningRecording.setText(getResources().getString(R.string.s_warning_restart_recording));
                        mTvWorningRecording.setBackgroundColor(getResources().getColor(R.color.color_F7CB66));
                        mLlWorningRecordingTime.setVisibility(View.GONE);
                        break;
                }
                return true;
            }
        });
    }


    private void onPlaySystemVedio() {
       /* if (player == null) {
            player = MediaPlayer.create(WarningActivity.this, R.raw.moren);
            player.start();
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {//监听是否播放完毕
                    player.release();//释放资源
                    player = null;
                }
            });
        } else if (player.isPlaying()) {
            player.stop();
            player.release();//释放资源
            player = null;
        }*/

        if (player != null && player.isPlaying()) {
            player.stop();
            player.release();//释放资源
            player = null;
        }
        player = MediaPlayer.create(WarningActivity.this, R.raw.moren);
        player.start();
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {//监听是否播放完毕
                player.release();//释放资源
                player = null;
            }
        });

    }


    private void onPlayVedio() {
        if (TextUtils.isEmpty(new SP().load(Constant.RECORD_PATH_ABSOULT, ""))) {
            ToastUtil.showShort("暂无录音内容");
        } else {
            /*if (player == null) {
                player = mAudioRecoderUtils.playRecord(new SP().load(Constant.RECORD_PATH_ABSOULT, ""));//播放
                player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {//监听是否播放完毕
                        player.release();//释放资源
                        player = null;
                    }
                });
            } else if (player.isPlaying()) {
                player.stop();
                player.release();//释放资源
                player = null;
            }*/


            if (player != null && player.isPlaying()) {
                player.stop();
                player.release();//释放资源
                player = null;
            }
            player = mAudioRecoderUtils.playRecord(new SP().load(Constant.RECORD_PATH_ABSOULT, ""));//播放
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {//监听是否播放完毕
                    player.release();//释放资源
                    player = null;
                }
            });


        }
    }


    //录音功能 初始化
  /*  private void initVedio(){
        view = View.inflate(this, R.layout.popup_window, null);
        //设置空白的背景色
        final WindowManager.LayoutParams lp = FaultActivity.this.getWindow().getAttributes();
        final PopupWindow mPop  = new PopupWindow(view);
        micImage=(ImageView)view.findViewById(R.id.iv_pro);
        recordingTime=(TextView)view.findViewById(R.id.recording_time);
        mAudioRecoderUtils = new AudioRecoderUtils();
        //录音回调
        mAudioRecoderUtils.setOnAudioStatusUpdateListener(new AudioRecoderUtils.OnAudioStatusUpdateListener() {

            //录音中....db为声音分贝，time为录音时长
            @Override
            public void onUpdate(double db, long time) {
                //根据分贝值来设置录音时话筒图标的上下波动
                ltime=time;
                micImage.getDrawable().setLevel((int) (3000 + 6000 * db / 100));
                recordingTime.setText(TimeUtils.getDateCoverString(time));
            }

            //录音结束，filePath为保存路径
            @Override
            public void onStop(String filePath) {
                if(ltime<1500){//判断，如果录音时间小于1.5秒，则删除文件提示，过短
                    File file = new File(filePath);
                    if(file.exists()){//判断文件是否存在，如果存在删除文件
                        file.delete();//删除文件
                        Toast.makeText(FaultActivity.this, "录音时间过短",Toast.LENGTH_SHORT).show();
                    }
                }else{
                    try {
                        //保存录音路径前先删除旧的文件
                        if(!Utils.StringEx(fault.getSoundpath())){
                            File file = new File(fault.getSoundpath());
                            if(file.exists()){//判断文件是否存在，如果存在删除文件
                                file.delete();//删除文件
                            }
                        }
                        fault.setSoundpath(filePath);
                        getDBManager().saveOrUpdate(fault);
                        Toast.makeText(FaultActivity.this, "录音保存在：" + filePath, Toast.LENGTH_SHORT).show();
                        recordingTime.setText("00:00");
                        ltime=0;
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        //Button的touch监听
        mButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()){

                    case MotionEvent.ACTION_DOWN:
                        lp.alpha = 0.4f;
                        FaultActivity.this.getWindow().setAttributes(lp);
                        mPop.setWidth(500);
                        mPop.setHeight(500);
                        mPop.showAtLocation(rl,Gravity.CENTER,0,0);
                        mAudioRecoderUtils.startRecord();

                        break;

                    case MotionEvent.ACTION_UP:
                        //恢复背景色
                        lp.alpha = 1f;
                        FaultActivity.this.getWindow().setAttributes(lp);
                        mAudioRecoderUtils.stopRecord();        //结束录音（保存录音文件）
                        mPop.dismiss();

                        break;
                }
                return true;
            }
        });

        //播放录音
        cButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Utils.StringEx(fault.getSoundpath())){
                    Toast.makeText(FaultActivity.this, "此故障信息暂无录音内容", Toast.LENGTH_SHORT).show();
                }else{
                    if(player==null){
                        player = mAudioRecoderUtils.playRecord(fault.getSoundpath());//播放
                        cButton.setBackgroundResource(R.drawable.zanting);
                        head_broadcast.setText("正在播放");
                        ivAnim.setBackgroundResource(R.drawable.anim);
                        drawable = (AnimationDrawable)ivAnim.getBackground();
                        drawable.start();
                        player.setOnCompletionListener(new OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {//监听是否播放完毕
                                cButton.setBackgroundResource(R.drawable.play);
                                head_broadcast.setText("点击播放");
                                player.release();//释放资源
                                player=null;
                                drawable.stop();
                                ivAnim.setBackgroundResource(R.drawable.bofang3);
                            }
                        });
                    }else if(player.isPlaying()){
                        player.stop();
                        player.release();//释放资源
                        player=null;
                        cButton.setBackgroundResource(R.drawable.play);
                        head_broadcast.setText("点击播放");
                        drawable.stop();
                        ivAnim.setBackgroundResource(R.drawable.bofang3);
                    }
                }
            }
        });
    }*/


}
